import React from 'react';
import {injectIntl, language} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Table, Modal, Alert, message} from 'antd';
import TextInput from 'Shared/components/TextInput';
import {
    PAGE,
    TABLE,
    FORM_BIG_OPTIONS,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT
} from '../constants';
import {conventSorter, getObjById} from './utils';
const ButtonGroup = Button.Group;
const FormItem = Form.Item;
import WrappedTag from '../common/WrappedTag';
import WrappedSelect from '../common/WrappedSelect';
import styles from './style.css';
import {baseDataStatus} from '../Enum';
import ModeDetail from './ModeDetail';
import CategoryTree from './QueryTreeForSelect';
import {PERMISSION} from './constants';
import {conventEnumValueToString} from '../utils';

const modalBodyStyle = {
    maxHeight: '60vh',
    overflowY: 'auto'
};
const statusList = baseDataStatus.toList(language);
class QueryPanel extends React.PureComponent {
    state = {
        showPanel: false,
        showPanelCategory: false,
        productCategoryId: ''
    };
    
    categorySelectable = item => item.isLeaf

    onCancelCategory = () => {
        this.setState({
            showPanelCategory: false,
            productCategoryId: ''
        });
        this.props.onCancelCategory();
    }
    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({
                ...conventSorter(sorter),
                pageIndex: PAGE.index
            });
    };
    onClickDetail = e => {
        const {id} = e.target.dataset;
        this.setState({
            currentId: id,
            showPanel: true
        });
    }

    onCancel = () => {
        this.setState({
            currentId: '',
            showPanel: false
        });
    }
    
    onClickBtn = () => {
        const {selectIds} = this.props.batchData;
        if(selectIds && selectIds.length > 0)
            this.setState({showPanelCategory: true});
        else
            message.warning(this.props.intl.formatMessage({
                id: 'queryPanel.form.select.updateProduct',
                defaultMessage: '请选择需要修改的产品'
            }));
    };
    
    onOk = () => {
        if(!this.state.productCategoryId)
            return message.warn(this.props.intl.formatMessage({
                id: 'queryPanel.form.select.category',
                defaultMessage: '请选择车型'
            }));
        this.setState({confirmLoading: true});
        return this.props.onOk(this.state.productCategoryId).then(success => {
            if(success)
                this.setState({
                    showPanelCategory: false,
                    productCategoryId: '',
                    confirmLoading: false
                });
            else
                this.setState({confirmLoading: false});
        });
    };

    onCategorySelect = productCategoryId => {
        this.setState({productCategoryId});
    };

    render() {
        const {isBatch, selectIds} = this.props.batchData;
        let rowSelection = null;
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.brandCode',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandCode',
                render: (text, r) => `(${r.brandCode})${r.brandName}`,
                sorter: true,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.code',
                    defaultMessage: '产品编号'
                }),
                dataIndex: 'code',
                render: (text, r) => <a key="detail" data-id={r.id} onClick={this.onClickDetail}>{text}</a>,
                sorter: true,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.name',
                    defaultMessage: '产品名称'
                }),
                dataIndex: 'name'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.color',
                    defaultMessage: '颜色'
                }),
                dataIndex: 'color'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.colorCode',
                    defaultMessage: '颜色码'
                }),
                dataIndex: 'colorCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(baseDataStatus, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.orderCycle',
                    defaultMessage: '订货周期'
                }),
                dataIndex: 'orderCycle'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.purchaseCycle',
                    defaultMessage: '采购周期'
                }),
                dataIndex: 'purchaseCycle'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.isUncommon',
                    defaultMessage: '是否小品种车型'
                }),
                dataIndex: 'isUncommon'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.isSpecial',
                    defaultMessage: '是否特殊车型'
                }),
                dataIndex: 'isSpecial'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.technicalNotes',
                    defaultMessage: '技术参数说明'
                }),
                dataIndex: 'technicalNotes'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.productCategoryStyle',
                    defaultMessage: '车型年款'
                }),
                dataIndex: 'productCategoryStyle'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.versionDescription',
                    defaultMessage: '版型描述'
                }),
                dataIndex: 'versionDescription'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.engineCylinder',
                    defaultMessage: '排量'
                }),
                dataIndex: 'engineCylinder'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.emissionStandard',
                    defaultMessage: '尾气排放标准'
                }),
                dataIndex: 'emissionStandard'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.transmission',
                    defaultMessage: '手自动'
                }),
                dataIndex: 'transmission'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark'
            }
        ];
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const detail = this.props.data.find(item => item.id === this.state.currentId) || {};
        const operations = [];
        if(isBatch)
            rowSelection = {
                type: 'checkbox',
                onChange: this.props.selectBatchIds,
                selectedRowKeys: selectIds,
            };
        else if(this.props.permissions.includes(PERMISSION.update))
            operations.push(<Button key="set" onClick={this.props.onClickBatch}>{this.props.intl.formatMessage({
                id: 'queryPanel.form.set.product',
                defaultMessage: '产品设置'
            })}</Button>);
        const changeEmptyText = {};
        if(this.props.errorMessage)
            changeEmptyText.locale = {
                emptyText: COMMON_TABLE_QUERY_FAIL_TEXT
            };
        return (
            <div>
                <ModeDetail
                    detail={detail}
                    onCancel={this.onCancel}
                    showPanel={this.state.showPanel} />
                <Form className="form-standard">
                    <Row>
                        <Col {...FORM_BIG_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.brand',
                                    defaultMessage: '品牌'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="brandId"
                                    value={this.props.conditions.brandId}
                                    options={this.props.brands}
                                    onChange={this.props.onConditionsChange}/>
                            </FormItem>
                        </Col>
                        <Col {...FORM_BIG_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.code',
                                    defaultMessage: '编号'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <TextInput
                                    name="code"
                                    value={this.props.conditions.code}
                                    onPressEnter={this.props.onConditionsPressEnter}
                                    onBlur={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_BIG_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.name',
                                    defaultMessage: '名称'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <TextInput
                                    name="name"
                                    value={this.props.conditions.name}
                                    onPressEnter={this.props.onConditionsPressEnter}
                                    onBlur={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_BIG_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.color',
                                    defaultMessage: '颜色'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <TextInput
                                    name="color"
                                    value={this.props.conditions.color}
                                    onPressEnter={this.props.onConditionsPressEnter}
                                    onBlur={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_BIG_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.colorCode',
                                    defaultMessage: '颜色码'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <TextInput
                                    name="colorCode"
                                    value={this.props.conditions.colorCode}
                                    onPressEnter={this.props.onConditionsPressEnter}
                                    onBlur={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_BIG_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.status',
                                    defaultMessage: '状态'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="status"
                                    value={this.props.conditions.status}
                                    options={statusList}
                                    onChange={this.props.onConditionsChange}/>
                            </FormItem>
                        </Col>
                        {this.props.categoryName
                            ? <Col {...FORM_BIG_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.category',
                                        defaultMessage: '分类'
                                    })}
                                    {...FORM_BIG_OPTIONS.item}>
                                    <WrappedTag className={styles.tagFontSize} color="blue"
                                        closable onClose={this.props.onCloseTag}>{this.props.categoryName}</WrappedTag>
                                </FormItem>
                            </Col> : null}
                    </Row>
                    <Row className="operation-buttons">
                        <Col span={10}>
                            <ButtonGroup>
                                <Button
                                    key="query"
                                    type="primary"
                                    onClick={this.props.querySearch}
                                    loading={this.props.loading}>
                                    {this.props.intl.formatMessage({
                                        id: 'queryPanel.btn.query',
                                        defaultMessage: '查询'
                                    })}
                                </Button>
                            </ButtonGroup>
                            <Button key="clear" onClick={this.props.onClickReset}>
                                {this.props.intl.formatMessage({
                                    id: 'queryPanel.btn.reset',
                                    defaultMessage: '重置'
                                })}
                            </Button>
                        </Col>
                    </Row>
                </Form>
                {isBatch && <Row className={styles.marginBottom}>
                    <Alert message={<span>
                        {selectIds.length === 0 ? this.props.intl.formatMessage({
                            id: 'queryPanel.form.select.product',
                            defaultMessage: '选择产品'
                        }) : `${this.props.intl.formatMessage({
                            id: 'queryPanel.form.selecton1',
                            defaultMessage: '已选择'
                        })} ${selectIds.length} ${this.props.intl.formatMessage({
                            id: 'queryPanel.form.selecton2',
                            defaultMessage: '个产品'
                        })}`}，
                        <a onClick={this.onClickBtn}>{this.props.intl.formatMessage({
                            id: 'queryPanel.form.set.category1',
                            defaultMessage: '设置分类'
                        })}</a>{this.props.intl.formatMessage({
                            id: 'queryPanel.form.set.category2',
                            defaultMessage: '，点击右侧关闭将退出操作'
                        })}</span>}
                    type="warning"
                    closable
                    showIcon
                    closeText={<span className={styles.closeText}>{this.props.intl.formatMessage({
                        id: 'queryPanel.form.closable',
                        defaultMessage: '关闭'
                    })}</span>}
                    onClose={this.props.changeBatchVisible} />
                </Row>}
                <Table
                    title={!this.props.categoryName && (isBatch || operations.length === 0) ? null : () => <Row>
                        <Col span={16}><Button.Group>{operations}</Button.Group></Col>
                    </Row>}
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    rowSelection={rowSelection}
                    {...changeEmptyText}
                    {...TABLE} />
                <Modal
                    visible={this.state.showPanelCategory}
                    confirmLoading={this.state.confirmLoading}
                    title={this.props.intl.formatMessage({
                        id: 'queryPanel.form.confirm',
                        defaultMessage: '分类绑定'
                    })}
                    maskClosable={false}
                    bodyStyle={modalBodyStyle}
                    onCancel={this.onCancelCategory}
                    onOk={this.onOk}>
                    <CategoryTree
                        locatedKey={this.state.productCategoryId}
                        selectable={this.categorySelectable}
                        onSelect={this.onCategorySelect} />
                </Modal>
            </div>
        );
    }
}

QueryPanel.propTypes = {
    brands: PropTypes.array.isRequired,
    changeBatchVisible: PropTypes.func.isRequired,
    selectBatchIds: PropTypes.func.isRequired,
    batchData: PropTypes.shape({
        isBatch: PropTypes.bool.isRequired,
        selectIds: PropTypes.array.isRequired
    }),
    conditions: PropTypes.object,
    intl: PropTypes.object,
    loading: PropTypes.bool,
    permissions: PropTypes.array,
    querySearch: PropTypes.func,
    onCancelCategory: PropTypes.func,
    onClickBatch: PropTypes.func,
    onClickExport: PropTypes.func,
    onClickReset: PropTypes.func,
    onConditionsChange: PropTypes.func,
    onConditionsPressEnter: PropTypes.func,
    onSelect: PropTypes.func,
};
import {connect} from 'react-redux';
import {
    saveQueryCondition,
    querySearch,
    resetQueryPanel,
    tableSearch,
    categorySearch,
    selectIds,
    onClickBindCategory,
    setBatchMode
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);

const getCategoryName = createSelector(
    state => state.getIn(['page', 'domainData', 'categories', 'data']),
    state => state.getIn(['page', 'appState', 'queryCondition', 'productCategoryId']),
    (categories, categoryId) => {
        if(!categoryId)
            return '';
        const category = getObjById(categories.toJS(), categoryId);
        return category ? category.name : '';
    }
);
const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    data => {
        const brands = data.toJS();
        return brands
            ? brands.map(item => ({
                value: item.id,
                text: `(${item.code})${item.name}`
            }))
            : [];
    }
);
const getBatchData = selectorFactory(['page', 'appState', 'batchData']);
const mapStateToProps = state => ({
    conditions: getConditions(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    permissions: getPermissions(state),
    data: getData(state),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    brands: getBrands(state),
    categoryName: getCategoryName(state),
    batchData: getBatchData(state),
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (value, name) => dispatch(saveQueryCondition(name, value)),
    onConditionsPressEnter: (value, name) => {
        dispatch(saveQueryCondition(name, value));
        dispatch(querySearch());
    },
    querySearch: () => dispatch(querySearch()),
    onClickReset: () => dispatch(resetQueryPanel()),
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onCloseTag: () => dispatch(categorySearch()),
    changeBatchVisible: () => dispatch(setBatchMode(false)),
    onClickBatch: () => dispatch(setBatchMode(true)),
    selectBatchIds: ids => dispatch(selectIds(ids)),
    onOk: productCategoryId => dispatch(onClickBindCategory(productCategoryId)).then(success => {
        if(success) {
            dispatch(querySearch());
            dispatch(setBatchMode(false));
        }
        return success;
    }),
    onCancelCategory: () => dispatch(setBatchMode(false))
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(QueryPanel));
